package com.example.smartcity.ui.act

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.smartcity.R
import com.example.smartcity.app.App
import com.example.smartcity.http.HttpCallback
import com.example.smartcity.http.LoginResp
import com.example.smartcity.utils.CommonUtil
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.layout_app_bar_common.*
import okhttp3.MediaType
import okhttp3.Request
import okhttp3.RequestBody


class LoginActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        tvAppBarTitle.text = "用户登录"
        ivAppBarLeft.setOnClickListener { finish() }
        btnLogin.setOnClickListener {
            var account = edtAccount.text.toString()
            var pwd = edtPwd.text.toString()
            if (account.isNullOrBlank()) {
                CommonUtil.showToast(this, edtAccount.hint.toString())
            } else if (pwd.isNullOrBlank()) {
                CommonUtil.showToast(this, edtPwd.hint.toString())
            } else {
                login(account, pwd)
            }
        }
    }

    private fun login(account: String, pwd: String) {
        val mediaType: MediaType? = MediaType.parse("application/json")
        val body = RequestBody.create(
            mediaType,
            "{\n\"username\":\"$account\",\n\"password\":\"$pwd\"\n}"
        )
        val request: Request = Request.Builder()
            .url("http://smart.ifast3.vipnps.vip/prod-api/api/login")
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .build()
        App.client.newCall(request).enqueue(object : HttpCallback() {
            override fun onSucceeded(s: String) {
                val data = App.json2Object<LoginResp>(s, LoginResp::class.java)
                data?.let {
                    App.appConfig.edit().putString("token", data.token).commit()
                    finish()
                }
            }
        })
    }

}